package com.design.observer;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.design.strategy.StrategyService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Observer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 观察者模式subject
 *
 * @author Zee
 * @date 2020年4月30日
 * @since v1.0
 */
@Component
public class ObserverSubject {
    private final List<ObserverComponent> observerList = new ArrayList<>();
    /**
     * 线程池
     */
    private ExecutorService executorService;

    public ObserverSubject() {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNamePrefix("Observer-").build();
        this.executorService = Executors.newFixedThreadPool(10,namedThreadFactory);
    }

    /**
     * 注册观察者实现类
     *
     * @param observerComponent
     */
    protected void registerObserver(ObserverComponent observerComponent) {
        observerList.add(observerComponent);
    }

    /**
     * 在实际项目使胳过程中一般会使用多线程的方式执行
     * 这里采用的线程池来管理线程
     */
    public void execute() {
        if (ObjectUtil.isNotEmpty(observerList)) {
            for (ObserverComponent observerComponent : observerList) {
                executorService.execute(() -> observerComponent.execute());
            }
        }

    }
}
